package com.lhsy.djcloud.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lhsy.djcloud.common.ReturnT;
import com.lhsy.djcloud.controller.vo.NoticeMessageVo;
import com.lhsy.djcloud.entity.Department;
import com.lhsy.djcloud.entity.NoticeMessage;
import com.lhsy.djcloud.entity.Upload;
import com.lhsy.djcloud.entity.User;
import com.lhsy.djcloud.entity.dto.UserDto;
import com.lhsy.djcloud.service.DepartmentService;
import com.lhsy.djcloud.service.NoticeMessageService;
import com.lhsy.djcloud.service.UploadService;
import com.lhsy.djcloud.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wangzw
 * @since 2020-09-14
 */
@RestController
@RequestMapping("/message")
@Api(value = "Server-API",tags = "消息管理")
public class NoticeMessageController extends BaseController{
    @Autowired private NoticeMessageService noticeMessageService;
    @Autowired private UploadService uploadService;
    @Autowired private DepartmentService departmentService;
    @Autowired private UserService userService;

    @ApiOperation(value = "获取当前用户的通知/任务/公告，按党组织分组")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public ReturnT getList(HttpServletRequest request,Integer type){
        UserDto currUser = getCurrUser(request);

        List<NoticeMessage>  ggMessages = noticeMessageService.selectAllMessage(currUser.getUserId(),type);
        ggMessages.forEach(noticeMessage -> {
            User user = userService.getById(noticeMessage.getSendUserId());
            User user1 = userService.getById(noticeMessage.getTargetUserId());
            Department department = departmentService.getById(user.getDeptId());
            Department department1 = departmentService.getById(user1.getDeptId());
            noticeMessage.setSendUserDeptName(Objects.isNull(department)?"":department.getDeptName());
            noticeMessage.setTargetUserDeptName(Objects.isNull(department1)?"":department1.getDeptName());
        });
        if (CollUtil.isEmpty(ggMessages)){
            return ReturnT.SUCCESS;
        }
        Map<Integer, List<NoticeMessage>> group = ggMessages.stream().collect(Collectors.groupingBy(NoticeMessage::getSendUserId));
        List<Map<String,Object>> params = Lists.newArrayList();
        Set<Integer> strings = group.keySet();
        for (Integer userId:strings){
            User user = userService.getById(userId);
            Department department = departmentService.getById(user.getDeptId());
            Map<String,Object> item = Maps.newHashMap();
            List<NoticeMessage> noticeMessages = group.get(userId);
            item.put("deptName",department.getDeptName());
            item.put("deptId",department.getId());
            item.put("sendUserId",user.getId());
            List<NoticeMessage> allMessage = noticeMessageService.selectUnReadMessage(currUser.getUserId(), user.getId(), type);
            item.put("size",CollUtil.isEmpty(allMessage)?0:allMessage.size());
            item.put("totalSize",noticeMessages.size());
            params.add(item);
        }
        return ReturnT.SUCCESS(params);
    }

    @ApiOperation(value = "获取当前用户的公告/简报/消息，按党组织分组")
    @RequestMapping(value = "/getList",method = RequestMethod.GET)
    public ReturnT<List<NoticeMessage>> getList(HttpServletRequest request,
                                                Integer sendUserId,
                                                Integer type,
                                                String params,
                                                @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                                                @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){
        UserDto currUser = getCurrUser(request);
        PageHelper.startPage(pageNo,pageSize);
        List<NoticeMessage> ggMessages = noticeMessageService.selectMessage(currUser.getUserId(),sendUserId,type,params);
        PageInfo<NoticeMessage> noticeMessagePageInfo = new PageInfo<>(ggMessages);
        noticeMessagePageInfo.getList().forEach(noticeMessage -> {
            User user = userService.getById(noticeMessage.getSendUserId());
            User user1 = userService.getById(noticeMessage.getTargetUserId());
            if (Objects.nonNull(user)){
                Department department = departmentService.getById(user.getDeptId());
                noticeMessage.setSendUserDeptName(Objects.isNull(department)?"":department.getDeptName());
            }
            if (Objects.nonNull(user1)){
                Department department1 = departmentService.getById(user1.getDeptId());
                noticeMessage.setTargetUserDeptName(Objects.isNull(department1)?"":department1.getDeptName());
            }


        });
        return ReturnT.SUCCESS(noticeMessagePageInfo);
    }

    @ApiOperation(value = "获取当前用户发送的公告/消息/简报")
    @RequestMapping(value = "/sendList",method = RequestMethod.GET)
    public ReturnT<List<NoticeMessage>> sendList(HttpServletRequest request,Integer type,
                                                 String params,
                                                 @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                                                 @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){
        UserDto currUser = getCurrUser(request);
        PageHelper.startPage(pageNo,pageSize);
        List<NoticeMessage> ggMessages = noticeMessageService.selectMyMessage(currUser.getUserId(),type,params);
        PageInfo<NoticeMessage> noticeMessagePageInfo = new PageInfo<>(ggMessages);
        noticeMessagePageInfo.getList().forEach(noticeMessage -> {
            User user = userService.getById(noticeMessage.getSendUserId());
            User user1 = userService.getById(noticeMessage.getTargetUserId());
            if (Objects.nonNull(user)&&Objects.nonNull(user1)){
                Department department = departmentService.getById(user.getDeptId());
                Department department1 = departmentService.getById(user1.getDeptId());
                noticeMessage.setSendUserDeptName(Objects.isNull(department)?"":department.getDeptName());
                noticeMessage.setTargetUserDeptName(Objects.isNull(department1)?"":department1.getDeptName());
            }
        });
        return ReturnT.SUCCESS(noticeMessagePageInfo);
    }

    @ApiOperation(value = "发送公告/消息/简报")
    @RequestMapping(value = "/send",method = RequestMethod.POST)
    public ReturnT send(HttpServletRequest request, @RequestBody NoticeMessageVo noticeMessageVo){
        //获取当前用户
        UserDto currUser = getCurrUser(request);
        //查询文件
        Upload upload = null;
        if (StrUtil.isNotEmpty(noticeMessageVo.getFileSHA1())){
            upload = uploadService.getBySha1(noticeMessageVo.getFileSHA1());
            if(Objects.isNull(upload)){
                return ReturnT.FAIL(ReturnT.FAIL_CODE,"文件不存在");
            }
        }
        Upload finalUpload = upload;
        noticeMessageVo.getTargetUserIds().forEach(integer -> {
            //添加文件列表
            NoticeMessage noticeMessage = new NoticeMessage();
            noticeMessage.setTenantId(currUser.getTenantId());
            noticeMessage.setType(noticeMessageVo.getType());
            noticeMessage.setSendUserId(currUser.getUserId());
            noticeMessage.setTargetUserId(integer);
            noticeMessage.setTitle(noticeMessageVo.getTitle());
            noticeMessage.setContent(noticeMessageVo.getContent());
            noticeMessage.setStatus(1);
            noticeMessage.setReadFlag(Boolean.FALSE);
            noticeMessage.setDeleteFlag(Boolean.FALSE);
            if (Objects.nonNull(finalUpload)){
                noticeMessage.setFileName(finalUpload.getName());
                noticeMessage.setFilePath(finalUpload.getPath());
            }
            noticeMessage.setCreateName(currUser.getUserName());
            noticeMessage.setCreateTime(new Date());
            noticeMessageService.save(noticeMessage);
        });
        return ReturnT.SUCCESS;
    }

    /**
     * 查看
     * @param id
     * @param request
     * @return
     */
    @ApiOperation(value = "查看详情")
    @RequestMapping(value = "/view/{id}",method = RequestMethod.POST)
    public ReturnT getList(@PathVariable Integer id, HttpServletRequest request){
        UserDto currUser = getCurrUser(request);
        //添加文件列表
        NoticeMessage noticeMessage = noticeMessageService.getById(id);
        if (Objects.nonNull(noticeMessage)){
            if (!noticeMessage.getSendUserId().equals(currUser.getUserId())&&!noticeMessage.getTargetUserId().equals(currUser.getUserId())){
                return ReturnT.FAIL;
            }
            if (currUser.getUserId().equals(noticeMessage.getTargetUserId())){
                noticeMessage.setReadFlag(Boolean.TRUE);
                noticeMessageService.updateById(noticeMessage);
            }

        }
        return ReturnT.SUCCESS(noticeMessage);
    }

    /**
     * 查看
     * @param id
     * @param request
     * @return
     */
    @ApiOperation(value = "删除(只能删除 我发送的)")
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
    public ReturnT delete(@PathVariable Integer id, HttpServletRequest request){
        UserDto currUser = getCurrUser(request);
        NoticeMessage noticeMessage = noticeMessageService.getById(id);
        if (Objects.nonNull(noticeMessage)){
            if (!noticeMessage.getSendUserId().equals(currUser.getUserId())){
                return ReturnT.FAIL;
            }
            noticeMessage.setDeleteFlag(Boolean.TRUE);
            noticeMessageService.updateById(noticeMessage);
        }
        return ReturnT.SUCCESS(noticeMessage);
    }
}

